package com.cskaoyan.transfer;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 创建日期: 2022/06/30 16:13
 *
 * @author ciggar
 *
 * 转账的案例，事务
 */
public class TransferDemo {

    public static void main(String[] args) throws SQLException {

        boolean ret = transfer("风华哥", "长风", 1000);

        if (ret) {
            System.out.println("转账成功！");
        }else {
            System.out.println("转账失败！");
        }

    }

    /**
     * 创建日期：2022/06/30 16:14
     * @param fromName  转账发起人
     * @param toName    转账受益人
     * @param money     转账金额
     * @return boolean  <true/> 表示转账成功； <false/> 表示转账失败
     * @author ciggar
     * 转账方法
     */
    public static boolean transfer(String fromName,String toName, Integer money) throws SQLException {

        Boolean flag = false;

        Connection connection = JDBCUtils.getConnection();

        try {
            // 开启事务
            connection.setAutoCommit(false);

            // 扣钱
            PreparedStatement preparedStatement = connection.prepareStatement("update account set money = money - ? where name = ? and money >= ?");

            preparedStatement.setInt(1, money);
            preparedStatement.setString(2, fromName);
            preparedStatement.setInt(3, money);

            int affectedRows = preparedStatement.executeUpdate();

            if (affectedRows < 1) {
               throw new RuntimeException("扣钱失败！");
            }
            preparedStatement.close();


//            int i = 1 / 0;


            // 加钱
            PreparedStatement addMoneyStatement = connection.prepareStatement("update account set money = money + ? where name = ?");

            addMoneyStatement.setInt(1, money);
            addMoneyStatement.setString(2, toName);

            int affectedRows2 = addMoneyStatement.executeUpdate();

            if (affectedRows2 < 1) {
                throw  new RuntimeException("加钱失败！");
            }
            addMoneyStatement.close();

            connection.commit();
            flag = true;

        }catch (Exception ex){
            ex.printStackTrace();
            // 回滚事务
            connection.rollback();
            flag = false;

        }
        return flag;

    }
}
